import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { login } from "@/utils/shuiwu/api";

export const baseURL = `/`;

const service = axios.create({
  baseURL,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

let loginPromise: Promise<string> | null = null;

// 请求拦截器
service.interceptors.request.use(
  async (config: any) => {
    if (config.url === "/geo/v2/city/lookup?location=银川") {
      config.baseURL = "/";
      config.headers["X-QW-Api-Key"] = "efc5709adc0a453793cdabf5b94245fb";
    }

    if (config.url === "/v2.6/Y2FpeXVuX25vdGlmeQ==/101.6656,39.2072/daily") {
      config.baseURL = "/";
    }

    const parts = config.url.split("/");
    const result = parts[1];

    if (
      result === "api-9000" &&
      config.url !== "/api-9000/prod-api/auth/ssoLogin"
    ) {
      const token = localStorage.getItem("TOKEN");
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      } else {
        if (!loginPromise) {
          loginPromise = login().then((res: any) => {
            localStorage.setItem("TOKEN", res.data);
            return res.data;
          });
        }
        const newToken = await loginPromise;
        config.headers["Authorization"] = `Bearer ${newToken}`;
      }
    }

    if (!config.headers) {
      throw new Error("Expected 'config' and 'config.headers' not to be undefined");
    }

    return config;
  },
  (error: any) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  async (response: AxiosResponse) => {
    if (
      response.config.url ===
      "/v2.6/Y2FpeXVuX25vdGlmeQ==/101.6656,39.2072/daily"
    ) {
      return response.data;
    }

    const { code, msg, result } = response.data;
    const originalRequest = response.config as any;

    if (code === 200 || code === 20005 || code === 20006 || code === 0 || result) {
      return response.data;
    }

    // token 过期，自动重新登录 + 重发请求
    if (code === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        if (!loginPromise) {
          loginPromise = login().then((res: any) => {
            const newToken = res.data;
            localStorage.setItem("TOKEN", newToken);
            return newToken;
          });
        }

        const newToken = await loginPromise;
        loginPromise = null;

        originalRequest.headers["Authorization"] = `Bearer ${newToken}`;
        return service(originalRequest); // 重发请求
      } catch (err) {
        loginPromise = null;
        return Promise.reject(err);
      }
    }

    // 二进制流数据（导出）
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    const { code, msg } = error.response?.data || {};
    return Promise.reject(new Error(msg || "请求失败"));
  }
);

export default service;